package com.atguigu.gmall.activity.listener;

import com.atguigu.gmall.activity.service.SeckillOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 * 秒杀下单的消息的消费者: 异步下单(抢单)
 */
@Component
@Slf4j
public class SeckillOrderAddListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    @RabbitListener(queues = "seckill_order_queue")
    public void seckillOrderAdd(Channel channel, Message message){
        //1 获取消息内容
        byte[] body = message.getBody();
        String userRecodeJsonString = new String(body);

        System.out.println(userRecodeJsonString);

        //2 手动确认消息
        //获取消息对象的属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            //3 调用业务层方法，秒杀真实下单
            seckillOrderService.realAddSeckillOrder(userRecodeJsonString);

            //确认消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                //4 处理异常，直接拒绝
                channel.basicReject(deliveryTag, false);
            } catch (Exception e1) {
                e1.printStackTrace();
                log.error("拒绝消息发生异常,秒杀排队的信息为:" + userRecodeJsonString) ;
            }
        }
    }
}
